/**
 * 二维码处理模块
 * 处理二维码的生成、扫描和打印功能
 */

import api from '../core/api.js';
import { formatDate } from '../core/utils.js';

class QRCodeManager {
    constructor() {
        this.scanner = null;
        this.isScanning = false;
    }

    // 生成二维码
    async generateQRCode(data) {
        try {
            const result = await api.generateQRCode(data);
            return result;
        } catch (error) {
            console.error('Failed to generate QR code:', error);
            throw error;
        }
    }

    // 初始化扫描器
    initScanner(videoElement, onResult) {
        if (!videoElement) {
            throw new Error('Video element is required');
        }

        this.scanner = {
            video: videoElement,
            canvas: document.createElement('canvas'),
            context: null,
            onResult: onResult
        };

        this.scanner.context = this.scanner.canvas.getContext('2d');
        this.scanner.canvas.width = videoElement.videoWidth;
        this.scanner.canvas.height = videoElement.videoHeight;
    }

    // 开始扫描
    async startScan() {
        if (!this.scanner) {
            throw new Error('Scanner not initialized');
        }

        if (this.isScanning) {
            return;
        }

        try {
            const stream = await navigator.mediaDevices.getUserMedia({
                video: { facingMode: 'environment' }
            });

            this.scanner.video.srcObject = stream;
            this.scanner.video.play();
            this.isScanning = true;

            this.scan();
        } catch (error) {
            console.error('Failed to start scanning:', error);
            throw error;
        }
    }

    // 扫描处理
    scan() {
        if (!this.isScanning) {
            return;
        }

        if (this.scanner.video.readyState === this.scanner.video.HAVE_ENOUGH_DATA) {
            this.scanner.canvas.width = this.scanner.video.videoWidth;
            this.scanner.canvas.height = this.scanner.video.videoHeight;
            this.scanner.context.drawImage(
                this.scanner.video,
                0,
                0,
                this.scanner.canvas.width,
                this.scanner.canvas.height
            );

            const imageData = this.scanner.context.getImageData(
                0,
                0,
                this.scanner.canvas.width,
                this.scanner.canvas.height
            );

            try {
                const code = jsQR(imageData.data, imageData.width, imageData.height);
                if (code) {
                    this.handleScanResult(code.data);
                }
            } catch (error) {
                console.error('Error processing QR code:', error);
            }
        }

        requestAnimationFrame(() => this.scan());
    }

    // 停止扫描
    stopScan() {
        if (!this.isScanning) {
            return;
        }

        this.isScanning = false;
        if (this.scanner.video.srcObject) {
            const tracks = this.scanner.video.srcObject.getTracks();
            tracks.forEach(track => track.stop());
            this.scanner.video.srcObject = null;
        }
    }

    // 处理扫描结果
    async handleScanResult(code) {
        try {
            const result = await api.scanQRCode(code);
            if (this.scanner.onResult) {
                this.scanner.onResult(result);
            }
            this.stopScan();
        } catch (error) {
            console.error('Failed to process scan result:', error);
            throw error;
        }
    }

    // 打印二维码
    async printQRCode(data) {
        try {
            const result = await api.printQRCode(data);
            return result;
        } catch (error) {
            console.error('Failed to print QR code:', error);
            throw error;
        }
    }

    // 生成物资二维码
    async generateInventoryQRCode(inventory) {
        const data = {
            type: 'inventory',
            id: inventory.id,
            name: inventory.name,
            category: inventory.category,
            expiryDate: inventory.expiryDate,
            timestamp: new Date().toISOString()
        };

        return this.generateQRCode(data);
    }

    // 生成急救车二维码
    async generateAmbulanceQRCode(ambulance) {
        const data = {
            type: 'ambulance',
            id: ambulance.id,
            plateNumber: ambulance.plateNumber,
            department: ambulance.department,
            timestamp: new Date().toISOString()
        };

        return this.generateQRCode(data);
    }

    // 解析二维码数据
    parseQRCodeData(code) {
        try {
            const data = JSON.parse(code);
            return {
                type: data.type,
                id: data.id,
                timestamp: new Date(data.timestamp),
                ...data
            };
        } catch (error) {
            console.error('Failed to parse QR code data:', error);
            throw error;
        }
    }
}

export default new QRCodeManager(); 